package cn.itsource.product.controller;

import cn.itsource.basic.utils.AjaxResult;
import cn.itsource.basic.utils.PageBean;
import cn.itsource.product.domain.Product;
import cn.itsource.product.query.ProductQuery;
import cn.itsource.product.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private IProductService productService;

    /**
     * 新增或者修改
     * @param product  如果id为空，则是新增，如果id不为空，则是修改
     * @return  返回成功还是失败
     */
    @PutMapping
    public AjaxResult saveOrUpdate(@RequestBody Product product){

        try {
            if (product.getId()==null){
                productService.save(product);
            }else {
                productService.update(product);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(e.getMessage());
        }
        return  AjaxResult.me();
    }


    @PostMapping("/onsale")
    public AjaxResult onsale(@RequestBody List<Product> products){
        try {
            //批量上架产品服务
            productService.onsale(products);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(e.getMessage());
        }
    }


    /**
     * 批量删除
     * @param products
     * @return
     */
    @PostMapping("/batchRemove")
    public AjaxResult batchRemove(@RequestBody List<Product> products){
        try {
            //批量删除
            productService.batchRemove(products);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            productService.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(e.getMessage());
        }
        return  AjaxResult.me();
    }



    @GetMapping
    public List<Product> queryAll(){
        return  productService.loadAll();
    }

    @PostMapping
    public PageBean<Product> queryPage(@RequestBody ProductQuery query){
        return  productService.queryPage(query);
    }



    //----------------------------以下是门户网站对应的接口-------------------------------------------------

    /**
     * 查看上架服务产品
     * @param query
     * @return
     */
    @PostMapping("/queryHomePage")
    public PageBean<Product> queryHomePage(@RequestBody ProductQuery query){
        return  productService.queryPage(query);
    }

    @GetMapping("/{id}")
    public Product queryById(@PathVariable("id") Long id){
        return  productService.loadById(id);
    }

}
